package com.v1.util;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;

/**
 * @author:luyang
 * @create_time:2008/11/04
 */
public class Toolkit {
	private static final Log log = LogFactory.getLog(Toolkit.class);

	private static Toolkit self;

	private ApplicationContext ac;

	private Toolkit() {
	}

	public static Toolkit getInstance() {
		if (self == null) {
			self = new Toolkit();
		}
		return self;
	}

	public void setApplicationContext(ApplicationContext applicationContext) {
		this.ac = applicationContext;
		init();
	}

	private void init() {
		refresh();
	}

	/**
	 * @return the applicationContext
	 */
	public ApplicationContext getApplicationContext() {
		return ac;
	}

	public Object getBean(String name) {
		return ac.getBean(name);
	}

	@SuppressWarnings("rawtypes")
	public void refresh() {
		log.debug("refresh.");
		Map beans = ac.getBeansOfType(LifeCycle.class);
		Collection values = beans.values();
		for (Object object : values) {
			((LifeCycle) object).refresh();
		}
	}

	public static String getErrorDetail(Throwable e) {
		ByteArrayOutputStream out = new ByteArrayOutputStream(1024 * 2);
		PrintStream sr = new PrintStream(out);
		// StackTrace to buffer
		e.printStackTrace(sr);
		// get error message
		String tmp = new String(out.toByteArray(), 0, out.size());
		return tmp;
	}

	public static String encodeZH(String str) throws UnsupportedEncodingException {
		String encode = URLEncoder.encode(str, "utf8");
		String r = encode.replaceAll("%", "-");
		return r;
	}

	public static String decodeZH(String str) throws UnsupportedEncodingException {
		String t = str.replaceAll("-", "%");
		String decode = URLDecoder.decode(t, "utf8");
		return decode;
	}

}
